package com.hybrid.jsbridge;

import android.text.TextUtils;
import com.hybrid.utils.TaoLog;
import com.hybrid.webview.WVWebView;

/**
 * 在此写用途
 *
 * @author: zhiwei
 * @date: 2017-10-09 22:24
 * @version: 9.1.0
 */
public class WVCallBackContext {
    private final static String TAG = "WVCallBackContext";
    private WVWebView webview;
    private String token;
    private String objectname;
    private String methodname;

    // private static final int maxlen = 1024;

    public WVCallBackContext(WVWebView webview) {
        this.webview = webview;
    }

    public WVCallBackContext(WVWebView webview, String token, String objectname, String methodname) {
        this.webview = webview;
        this.token = token;
        this.objectname = objectname;
        this.methodname = methodname;
    }

    public WVWebView getWebview() {
        return webview;
    }

    public void setWebview(WVWebView webview) {
        this.webview = webview;
    }

    public String getToken() {
        return token;
    }

    public void setToken(String token) {
        this.token = token;
    }

    /**
     * js事件的直接通知回调
     *
     * @param eventName
     *            事件名称
     * @param eventParam
     *            传给前端js的参数，约定json格式
     */
    public void fireEvent(final String eventName, String eventParam) {
        TaoLog.d(TAG, "call fireEvent ");
        //if (WVMonitorService.getJsBridgeMonitor() != null) {
        //    webview.post(new Runnable() {
        //        @Override
        //        public void run() {
        //            WVMonitorService.getJsBridgeMonitor().didFireEvent(webview.getUrl(), eventName);
        //        }
        //    });
        //}
        callback(webview, String.format("window.WindVane.fireEvent && window.WindVane.fireEvent('%s', '%%s', %s);", eventName, token), eventParam);
    }

    public static void fireEvent(final WVWebView webview, final String eventName, String eventParam) {
        TaoLog.d(TAG, "call fireEvent ");
        //if (WVMonitorService.getJsBridgeMonitor() != null) {
        //    webview.post(new Runnable() {
        //        @Override
        //        public void run() {
        //            WVMonitorService.getJsBridgeMonitor().didFireEvent(webview.getUrl(), eventName);
        //        }
        //    });
        //}
        callback(webview, String.format("window.WindVane.fireEvent && window.WindVane.fireEvent('%s', '%%s', %s);", eventName, null), eventParam);
    }

    public void fireEvent(String eventName) {
        fireEvent(eventName, "{}");
    }

    public void success() {
        success(WVResult.RET_SUCCESS);
    }

    /**
     * @see #success(String)
     */
    public void success(WVResult result) {
        if (result != null) {
            result.setSuccess();
            success(result.toJsonString());
        }
    }

    /**
     * 成功回调
     *
     * @param retString
     *            返回给前端js的结果，约定json格式
     * @see #error(String)
     */
    public void success(String retString) {
        TaoLog.d(TAG, "call success ");
        //if (WVMonitorService.getJsBridgeMonitor() != null) {
        //    webview.post(new Runnable() {
        //        @Override
        //        public void run() {
        //            WVMonitorService.getJsBridgeMonitor().didCallBackAtURL(objectname, methodname, webview.getUrl(), WVResult.SUCCESS);
        //        }
        //    });
        //}
        callback(webview, String.format("javascript:window.WindVane.onSuccess(%s,'%%s');", token), retString);
    }

    public void error() {
        error("{}");
    }

    /**
     * @see #error(String)
     */
    public void error(WVResult result) {
        if (result != null) {
            error(result.toJsonString());
        }
    }

    /**
     * 失败回调
     *
     * @see #success(String)
     */
    public void error(String retString) {
        TaoLog.d(TAG, "call error ");
        //if (WVMonitorService.getJsBridgeMonitor() != null) {
        //    webview.post(new Runnable() {
        //        @Override
        //        public void run() {
        //            WVMonitorService.getJsBridgeMonitor().didCallBackAtURL(objectname, methodname, webview.getUrl(), WVResult.FAIL);
        //        }
        //    });
        //}
        callback(webview, String.format("javascript:window.WindVane.onFailure(%s,'%%s');", token), retString);
    }

    private static void callback(final WVWebView webview, String js, String retString) {
        retString = TextUtils.isEmpty(retString) ? "{}" : retString;
        retString = formatJsonString(retString);
        try {
            js = String.format(js, retString);
            final String jsCode = js;
            webview.post(new Runnable() {
                @Override
                public void run() {
                    webview.evaluateJavascript(jsCode);
                }
            });
        } catch (Exception e) {
            TaoLog.e(TAG, "callback error. " + e.getMessage());
        }
    }

     @Deprecated
     private void callback(String js) {
         if (TaoLog.getLogStatus()) {
             TaoLog.d(TAG, "callback: " + js);
         }
         if (webview == null) { return; }
         try {
             webview.loadUrl(js);
         } catch (Exception e) {
             TaoLog.e(TAG, "callback error. " + e.getMessage());
         }
     }

    private static String formatJsonString(String str) {
        // 修复诸如 "{'a':'abc\"123'}" 传递给前端时\丢失的问题
        return str.replace("\\", "\\\\").replace("'", "\\'");
    }
}
